package com.hue.concurrent.day04;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/*
    使用锁超时来解决哲学家就餐问题
 */
public class Demo10 {
    public static void main(String[] args) {
        ReentrantLock a = new ReentrantLock();
        ReentrantLock b = new ReentrantLock();
        ReentrantLock c = new ReentrantLock();
        ReentrantLock d = new ReentrantLock();
        ReentrantLock e = new ReentrantLock();
        new People(a, b, 0).start();
        new People(b, c, 1).start();
        new People(c, d, 2).start();
        new People(d, e, 3).start();
        new People(e, a, 4).start();
    }

    public static class People extends Thread {
        private final ReentrantLock left;
        private final ReentrantLock right;

        public People(ReentrantLock left, ReentrantLock right, int id) {
            super(Name.get(id).getName());
            this.left = left;
            this.right = right;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    if (left.tryLock(1, TimeUnit.SECONDS)) {
                        try {
                            if (right.tryLock(2, TimeUnit.SECONDS)) {
                                try {
                                    System.out.println(Thread.currentThread().getName() + "开始吃饭...");
                                    Thread.sleep(1000);
                                } finally {
                                    right.unlock();
                                }
                            }
                        } finally {
                            left.unlock();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public static enum Name {
        ONE("张三"), TWO("李四"), THREE("王五"), FOUR("钱六"), FIVE("田七");

        private String name;

        Name(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public static Name get(int i) {
            Name[] names = Name.values();
            return names[i];
        }
    }
}
